package com.majun.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author mj
 * @2025/2/10 2:31
 */
public class gitTest3 {

    public static void main(String[] args) {
        String repoPath = "F:/majungitdiff/majun2024";
        String commitId1 = "0f314052dd8dc36648cdb1d9ae9b8e21fbf6975e";
        String commitId2 = "2a55ff6ec53c9c7f7b9846d29f6be7105a8dbfdc";

        try {
            File workingDir = new File(repoPath);
            if (!workingDir.exists() || !workingDir.isDirectory()) {
                throw new IOException("The specified repository directory does not exist or is not a directory.");
            }
            //dasdadsadasdsdddd
            //git diff test
            //ccc
            ProcessBuilder processBuilder = new ProcessBuilder(
                    "git", "--git-dir=" + repoPath + "/.git", "--work-tree=" + repoPath, "diff", "--stat", commitId1, commitId2
            );
            processBuilder.redirectErrorStream(true); // Merge error and standard output

            // Start the process and capture its output
            Process process = processBuilder.start();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                Pattern pattern = Pattern.compile("^\\s*(\\d+)\\s+(\\d+)\\s+\\d+\\s+(.+)$");

                while ((line = reader.readLine()) != null) {
                    Matcher matcher = pattern.matcher(line);
                    if (matcher.matches()) {
                        int addedLines = Integer.parseInt(matcher.group(1));
                        int deletedLines = Integer.parseInt(matcher.group(2));
                        String fileName = matcher.group(3).trim();

                        System.out.printf("File: %s, Added Lines: %d, Deleted Lines: %d%n", fileName, addedLines, deletedLines);
                    }
                }
            }

            // Wait for the process to complete and check the exit code
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new IOException("Git diff command failed with exit code: " + exitCode);
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
